<script setup lang="ts">
import DeviceTable from '@/components/DeviceTable.vue'
import VideoItem from '@/components/VideoItem.vue'
import CameraVideo from '@/components/CameraVideo.vue'
import { searchInfraredMissionListApi, getInfraredMissionDetailApi } from '@/api/infrared'
import emitter from '@/utils/eventBus'
import { ref, watch, reactive, inject, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import fixTime from '@/utils/fixTime'
import { formatTime } from '@/utils/common'

import axios from 'axios'

const props = defineProps({
  yard: {
    type: Number,
    default: 1
  },
  canvasId: {
    type: String,
    default: ''
  }
})

// 定义变量
const dialogTableVisible = ref(false)

const yard = ref(0)
const canvasId = ref('')
// 展示某一个报警的录像
const showItem = ref(false)
// 设备状态信息
const state = ref('')
// 时间
const time = ref([ '', '' ])
// 位置
const key = ref('')
// 视频地址
const videoUrl = reactive({
  0: '',
  1: '',
  2: '',
  3: '',
  4: '',
  5: '',
  6: '',
  7: '',
  8: '',
  9: '',
  10: '',
  11: ''
})
// 视频地址
const ports:any = ref([])
// 红外视频地址
const infraredPorts: any = ref([])
// 可见光视频地址
const visibleAPorts: any = ref([])
// 状态options
const stateOptions = [
  {
    value: '正常状态',
    label: '正常状态'
  },
  {
    value: '一级警报',
    label: '一级警报'
  },
  {
    value: '二级警报',
    label: '二级警报'
  }
]
// 设备数据源
const deviceData = ref([])
// 当前页码
const currentPage = ref(1)
const pageSize = ref(10)
// 数据总数
const currentTotal = ref(0)
// const videoUrl = ref('../assets/video/test2.mp4')

// 监听器
watch(currentPage, async (nv, ov) => {
  let data = {
    startTime: time.value[0] ? fixTime(time.value[0]) : '',
    endTime: time.value[1] ? fixTime(time.value[1]) : '',
    maxResultCount: 10,
    skipCount: (nv - 1) * 10
  }
  getInfraredAlarmList(data)
})  

// 定义方法
onMounted(() => {
  emitter.on('FlameCoalData', getInfraredData)
})

// 切换实时视频和录像
const showItemVideo = () => {
  showItem.value = true
}

// 展示设备列表弹框
const showInfrarTable = async (name:number, id:string) => {
  yard.value = name
  canvasId.value = id
  let data = {
    // maxResultCount: 10,
    // skipCount: 0
  }
  getInfraredAlarmList(data)
  initVideo()
  dialogTableVisible.value = true
}

// 改变时间范围
const changeTime = (value:any) => {
  console.log('时间范围----->', value, time)
}

// 查询设备信息
const queryDevice = async () => {
  if (!state.value && (!time.value[0] || !time.value[1]) && !key.value) {
    getInfraredAlarmList({})
    return
  } else {
    let data = {
      startTime: time.value[0] ? fixTime(time.value[0]) : '',
      endTime: time.value[1] ? fixTime(time.value[1]) : '',
      maxResultCount: 10,
      skipCount: 0
    }
    console.log('点击查询---->', time.value[0], time.value[1], data)
    getInfraredAlarmList(data)
  }
 
}

// 获取数据列表
const getInfraredAlarmList = async (data:any) => {
  let res = await searchInfraredMissionListApi(data)
  if (res.code === -1) {
    ElMessage({
      // message: `${res.message}`,
      message: '网络请求中断获取数据错误！',
      type: 'warning'
    })
    return
  }
  res.items.forEach((item:any, index:number) => {
    res.items[index].creationTime = formatTime(item.creationTime)
  })
  deviceData.value = res.items
  currentTotal.value = res.totalCount
}

const handlePlanSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  if (!state.value && (!time.value[0] || !time.value[1]) && !key.value) {
    getInfraredAlarmList({})
    return
  } else {
    let data = {
      startTime: time.value[0] ? fixTime(time.value[0]) : '',
      endTime: time.value[1] ? fixTime(time.value[1]) : '',
      maxResultCount: 10,
      skipCount: 0
    }
    getInfraredAlarmList(data)
  }
}

// 展示选中项的视频
const showVideo = (row:any) => {
  row.forEach((item:any, index:number) => {
    // videoUrl[index] = item.lightVideoFtpPath
    // videoUrl[index + 6] = item.lightVideoPath
    videoUrl[index] = item.thermalVideoPath
    videoUrl[index + 6] = item.lightVideoPath
  })
  console.log('视频录像地址--------->', videoUrl)
  
}

// 清除筛选条件
const clearQueryData = () => {
  state.value = ''
  time.value[0] = ''
  time.value[1] = ''
  key.value = ''
}

// 关闭弹框
const closeDialog = () => {
  state.value = ''
  time.value[0] = ''
  time.value[1] = ''
  infraredPorts.value = []
  visibleAPorts.value = []

  // console.log('关闭弹框---->')
  // for (let i = 0; i < 6; i++) {
  //   const video1:any = document.getElementById(`infraredMoitop${i}`)
  //   const context1 = video1.getContext('2d')
  //   context1.clearRect(0, 0, video1.width, video1.height)
  //   const video2:any = document.getElementById(`visibleLight${i}`)
  //   const context2 = video2.getContext('2d')
  //   context2.clearRect(0, 0, video2.width, video2.height)
  // }

  showItem.value = false
}

// 获取红外报警信息
const getInfraredData = (FlameCoalData: any) => {
  // console.log('连接状态数据----->', FlameCoalData)
}

// 加载视频流
const initVideo = () => {
  // console.log('时间范围----->', yard.value, canvasId.value)
  // setTimeout(() => {
  //   for (let i = 0; i < 6;i++) {
  //     // console.log('加载红外监控视频流qqqqq------>', props.yard, i, window.Glob.yard1InfraredVideo[i])
  //     const video1 = document.getElementById(`${props.canvasId}infraredMoitop${i}`)
  //     let url1
  //     if (!props.yard) {
  //       url1 = window.Glob.yard1InfraredVideo[i]
        
  //     } else {
  //       url1 = window.Glob.yard2InfraredVideo[i]
  //     }
      
  //     new window.JSMpeg.Player(url1, {
  //       canvas: video1,
  //       disableWebAssembly: true,
  //       disableGl: true,
  //       autoplay: true,
  //       loop: true
  //     })
  //     const video2 = document.getElementById(`${props.canvasId}visibleLight${i}`)
  //     let url2
  //     if (!props.yard) {
  //       url2 = window.Glob.yard1VisibleLight[i]
  //     } else {
  //       url2 = window.Glob.yard2VisibleLight[i]
  //     }
  //     new window.JSMpeg.Player(url2, {
  //       canvas: video2,
  //       disableWebAssembly: true,
  //       disableGl: true,
  //       autoplay: true,
  //       loop: true
  //     })
  //     console.log('监控视频地址----->', url1, url2)
  //   }
  // }, 100)

  if (!yard.value) {
    Promise.allSettled([
      getPort({ ipAddress: '192.16.11.120', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.121', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.122', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.123', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.124', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.125', userName: 'admin', password: 'BHDC2024' })
    ]).then(res => {
      // console.log('A煤棚监控----->', res)
      handleRes(res)
    })
  } else {
    Promise.allSettled([
      getPort({ ipAddress: '192.16.11.126', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.127', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.128', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.129', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.30', userName: 'admin', password: 'BHDC2024' }),
      getPort({ ipAddress: '192.16.11.31', userName: 'admin', password: 'BHDC2024' })
    ]).then(res => {
      // console.log('B煤棚监控----->', res)
      handleRes(res)
    })
  }
}

// 获取视频流地址
const getPort = async (cameraInfo: { ipAddress: string, userName: string, password: string }) => {
  const res = await axios.post('http://192.16.10.78:5550/showVideo', {
    ipAddress: cameraInfo.ipAddress,
    userName: cameraInfo.userName,
    password: cameraInfo.password
  })
  // console.log('getPort-------->', res)
  return res
}

// 视频流地址整合
const handleRes = (res:any) => {
  ports.value = []
  infraredPorts.value = []
  visibleAPorts.value = []
  res.forEach((item:any) => {
    if (item.value.status === 200 && item.value.data && item.value.data.port1) {
      infraredPorts.value.push(item.value.data.port1)
      visibleAPorts.value.push(item.value.data.port2)
    }
  })
  // console.log('ports--------->', ports.value)
}

defineExpose({
  showInfrarTable
})
</script>
<template>
  <el-dialog
    v-model="dialogTableVisible"
    class="infrar-dialog"
    @close="closeDialog"
  >
    <template #header>
      <div class="infrar-header-box">
        <div class="title">
          红外巡检
          &ensp;
          <span @click="initVideo">刷新</span>
        </div>
      </div>
    </template>
    <div class="info-main-box">
      <div
        v-if="showItem"
        class="video-box"
      >
        <div class="video1">
          <div class="video-item">
            <video-item :video-url="videoUrl[0]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[1]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[2]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[3]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[4]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[5]" />
          </div>
        </div>
        <div class="video2">
          <div class="video-item">
            <video-item :video-url="videoUrl[6]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[7]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[8]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[9]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[10]" />
          </div>
          <div class="video-item">
            <video-item :video-url="videoUrl[11]" />
          </div>
        </div>
      </div>
      <div
        v-else
        class="real-time-monitor"
      >
        <div
          v-if="infraredPorts.length"
          class="monitor1"
        >
          <div
            v-for="item in infraredPorts"
            :key="item"
          >
            <!-- <canvas :id="props.canvasId + 'infraredMoitop0'" /> -->
            <camera-video :port="item" />
          </div>
        </div>
        <div
          v-if="visibleAPorts.length"
          class="monitor2"
        >
          <div
            v-for="item in visibleAPorts"
            :key="item"
          >
            <!-- <canvas :id="props.canvasId + 'infraredMoitop0'" /> -->
            <camera-video :port="item" />
          </div>
          <!-- <div>
            <camera-video :port="ports[3]" />
          </div>
          <div>
            <camera-video :port="ports[5]" />
          </div>
          <div>
            <camera-video :port="ports[7]" />
          </div>
          <div>
            <camera-video :port="ports[9]" />
          </div>
          <div>
            <camera-video :port="ports[11]" />
          </div> -->
        </div>
      </div>
      <div class="filter-box">
        <!-- <el-select
            v-model="state"
            class="infrar-state"
            placeholder="请选择状态"
          >
            <template #prefix>
              <div>状态</div>
            </template>
            <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select> -->
        <!-- <el-input
            v-model="key"
            class="infrar-posi"
            placeholder="请输入位置"
          >
            <template #prefix>
              <div>位置</div>
            </template>
          </el-input> -->
        <!-- <el-date-picker
            v-model="time"
            class="infrar-time"
            type="datetime"
            prefix-icon
            placeholder="请选择时间"
          /> -->
        <div class="date-picker-box">
          <el-date-picker
            v-model="time"
            class="infrar-time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </div>
        <div class="btn-box">
          <div
            class="search-btn"
            @click="queryDevice"
          >
            查询
          </div>
          <div
            class="clear-btn"
            @click="clearQueryData"
          >
            重置
          </div>
        </div>
      </div>
      <div class="device-table">
        <DeviceTable
          :device-data="deviceData"
          :show-video="showVideo"
          :show-item-video="showItemVideo"
        />
      </div>
      <div
        v-if="currentTotal"
        class="pagination-box"
      >
        <!-- <el-pagination
            v-model:current-page="currentPage"
            class="device-page"
            :page-size="50"
            :pager-count="6"
            layout="prev, pager, next"
            :total="currentTotal"
          /> -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="currentTotal"
          @size-change="handlePlanSizeChange"
        />
      </div>
    </div>
  </el-dialog>
</template>

<style lang="scss">
  
  .infrar-box {
    height: 32px;
    margin-top: 3px;
    color: #ee7200ff;
    text-align: center;
  }
  .circle-box {
    width: 24px;
    height: 24px;
    margin-top: 2px;
    margin-left: 4px;
    line-height: 24px;
    text-align: center;

    /* background: linear-gradient(180deg, #EE7200 0%, #FFB775 100%); */
    background: #ffeddcff;
    border-radius: 24px;
    box-shadow: 0 2px 4px 0 #bbd2ff;
    opacity: 1;
  }
  .info-main-box {
    /* border: 1px solid red; */
    .video-box {
      display: flex;
      justify-content: space-between;
      >div {
        display: flex;
        flex-wrap: wrap;
        width: 474px;
        height: 262px;
        >div {
          width: 153px;
          height: 126px;
          margin-left: 3px;

          /* border: 1px solid red; */
        }
      }
    }
    .real-time-monitor {
      display: flex;
      width: 100%;
      height: 262px;

      /* border: 1px solid red; */
      >div {
        display: flex;
        flex-wrap: wrap;
        width: 50%;
        height: 100%;

        /* border: 1px solid blue; */
        >div {
          width: 153px;
          height: 126px;
          margin-left: 3px;
          border: 1px solid green;
          >canvas {
            width: 153px;
            height: 126px;
          }
        }
      }
    }
    .filter-box {
      display: flex;
      justify-content: space-between;
      height: 32px;
      margin-top: 24px;

      /* border: 1px solid red; */
      .date-picker-box {
        width: 400px;
      }
      .btn-box {
        display: flex;
        align-items: center;
        margin-left: 30px;
        >div {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50px;
          height: 30px;
          margin-top: 6px;
          font-weight: 600;
          font-size: 14px;
          font-family: PingFang, sans-serif;
          line-height: 20px;
          text-align: center;
          background-clip: text;
          border: 1px solid #1D41FF;
        }
        .search-btn {
          color: #fff;
          background: #1D41FF;
        }
        .search-btn:hover {
          cursor: pointer;
        }
        .clear-btn {
          width: 50px;
          margin-left: 15px;
        }
        .clear-btn:hover {
          color: #fff;
          background: #1D41FF;
          cursor: pointer;
        }
      }
      .icon-divider {
        width: 0 !important;
        height: 12px !important;
        margin-top: 10px !important;
        border: 1px solid #A9AEB8 !important;
      }
    }
    .device-table {
      width: 957px;
      height: 330px;
      margin-top: 16px;

      /* border: 1px solid red; */
    }
    .pagination-box {
      display: flex;
      justify-content: end;
      height: 30px;

      /* margin-top: 16px; */
      text-align: end;
    }
  }
  #infaredSecondary {
    transform: rotate(-180deg);
  }
.infrar-item-main-box:hover {
  cursor: pointer;
}
</style>

<style lang="scss">
.infrar-dialog {
  width: 1000px;
  height: 760px;
  .infrar-header-box {
    .title {
      width: 320px;
      height: 28px;
      padding-left: 15px;
      color: #4e5969;
      font-weight: 600;
      font-size: 20px;
      font-family: PingFang,sans-serif;
      line-height: 23px;
      background-clip: text;
      >span {
          color: #0094FFFF;
          font-size: 14px;
          cursor: pointer;
        }
    }
  }
  .el-dialog__body {
    height: 630px;
    padding-top: 0;

    /* border: 1px solid red; */
  }
}
.infrar-state,
.infrar-posi,
.infrar-time {
  width: 200px;
  height: 32px;

  /* border: 1px solid red; */
}
.infrar-posi,
.infrar-time {
  margin-left: 16px;
}
.device-page {
  /* margin-left: 615px; */
}

</style>
